package io.web.bi;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.RequestLine;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * RestClientDemo.
 *
 * @date 2023-07-18
 */
public class RestClientDemo {

    RestClient restClient;

    @BeforeEach
    public void connect() {
        restClient = RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http")).build();
    }

    @AfterEach
    public void close() throws Exception {
        restClient.close();
    }

    @Test
    public void response() throws Exception {
        Response response = restClient.performRequest(new Request("GET", "/"));
        RequestLine requestLine = response.getRequestLine();
        HttpHost host = response.getHost();
        int statusCode = response.getStatusLine().getStatusCode();
        Header[] headers = response.getHeaders();
        String responseBody = EntityUtils.toString(response.getEntity());
        System.out.println();
    }

    @Test
    void employee() throws Exception {
        Request request = new Request("POST", "/megacorp/employee/_search");
        Response response = restClient.performRequest(request);
        String responseBody = EntityUtils.toString(response.getEntity());
        System.out.println(responseBody);
    }

    /**
     * 创建doc
     */
    @Test
    void create() throws Exception {
        Request request = new Request("POST", "/cat/_doc");
        String body = "{\n" +
                "  \"name\" :\"mycat\"\n" +
                "}";
        request.setJsonEntity(body);

        Response response = restClient.performRequest(request);
        String responseBody = EntityUtils.toString(response.getEntity());
        System.out.println(responseBody);
        Map map = JSONUtil.toBean(responseBody, Map.class);
        Object id = map.get("_id");
        System.out.println(id); // 6EX8bIkBnPdjlNHZvpVd
    }
}
